// 引入数据库
const {
  mysqlFun
} = require('../mysql/mysql');
const request = require('request');
// 导入交友宣言页面
exports.friend = function (app) {
  // 拉取交友页面的内容
  app.post('/friend', (req, res) => {
    const sql = `select * from friend`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        // 把friendtrue===1的内容展示出来
        let setData = [];
        for (let index = 0; index < data.length; index++) {
          const element = data[index];
          if (element.friendtrue === 1) {
            setData.push(element)
          }
        }
        // 反转字符串，让新的留言出现在最上方
        setData.reverse()
        res.json({
          code: 'F0001',
          msg: '获取数据成功',
          data: setData
        })
      }
    }
    mysqlFun(sql, obj);
  })

  //提交页面内容
  app.post('/friendText', (req, res) => {
    let usersql = `select * from userdata where id=${req.body.id}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      let qqUser = encodeURI(req.body.userQq)
      request(`http://api.o5tc.cn/qqxt/api.php?qq=${qqUser}`, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          let user = JSON.parse(body).name

          let sql = `INSERT INTO friend(frienduser,user,userword,sex,friendtext) value (${req.body.userQq},'${user}','${data[0].autograph}',${data[0].sex},'${req.body.friendText}')`;

          function obj(data) {
            if (data === undefined) {
              return;
            }
            res.json({
              code: 'F0002',
              msg: '个性宣言写入成功'
            })
          }
          mysqlFun(sql, obj);
        }
      })
    }
    mysqlFun(usersql, obj);
  })

  // 拉取交友页面的内容
  app.post('/friendAll', (req, res) => {
    const sql = `select * from friend`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        // 把friendtrue===1的内容展示出来
        let setTrue = [];
        let setFalse = [];
        for (let index = 0; index < data.length; index++) {
          const element = data[index];
          if (element.friendtrue === 1) {
            // 未审核
            setTrue.push(element)
          } else {
            // 已审核
            setFalse.push(element)
          }
        }
        // 反转字符串，让新的留言出现在最上方
        setTrue.reverse()
        setFalse.reverse()
        res.json({
          code: 'F0001',
          msg: '获取数据成功',
          friendtrue: setTrue,
          friendfalse: setFalse
        })
      }
    }
    mysqlFun(sql, obj);
  })

  // 过审
  app.post('/setFriendAll', (req, res) => {
    const sql = `update friend set friendtrue=${req.body.isF} WHERE id=${req.body.id}`;

    function obj(data) {
      if (data === undefined) {
        return;
      }
      if (data.length !== 0) {
        res.json({
          code: 'S0001',
          msg: '审核成功',
        })
      }
    }
    mysqlFun(sql, obj);
  })
}